<?php
namespace Views;
/**
 * File holds class for generating feedback view
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Views
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class Feedback extends Page {
    /**
     * Appropriate service object
     * @var \Services\Feedback
     */
	private $_service;
	
	/**
	 * Constructor initiates super setUp method and appropriate service class
	 */
	public function __construct() {
		$this->setUp();
		$this->_service = new \Services\Feedback();
	}
	
	/**
	 * Method shows feedback form to user. Title is generated from attribute
	 * If no match is found, attribute will be used as name!
	 * @param var $business Business identifier code
	 * @return void
	 */
	public function viewForm($business) {
	    try {
    	    //FIXME: following throws exception. catch it and redirect to error (todo) page
    		$this->_getBusinessDetailsForFeedback($business);
    		//mark page as "regular"
    		$this->_smarty->assign('mobile', 0);
    		//show feedback form template
    		$this->displayStatic('feedbackForm.tpl');
	    } catch (\Exception $e) {
	        //error is already logged to syslog, only inform user!
            $this->_pagePanic();
	    }
		
	}

	/**
	 * Method shows mobile view for feedback
	 * @param var $business Business identifier code
	 */
	public function viewPortableForm($business) {
	    try {
    	    $this->_getBusinessDetailsForFeedback($business);
    	    //mark page as "mobile"
    	    $this->_smarty->assign('mobile', 1);
    	    //assign empty string as messages, otherwise error is generated that
    	    //variable is not set 
    	    $this->_smarty->assign('messages', '');
    	    //read feedback form into content object
    	    $this->_smarty->assign('content', $this->_smarty->fetch('feedbackForm.tpl'));
    	    //show page in portable wrapper
	    } catch (\Exception $e) {
	        //error is already logged to syslog, only inform user!
	        $this->_smarty->assign('messages', array('error' => 'Internal error occurred! Check back later!'));
	        $this->_smarty->assign('content', '');
	    }
	    $this->_smarty->display('portable.tpl');
	}
	
	/**
	 * Method assigns business and tabletalker variable to template accourding
	 * to business code
	 * @param var $business Business code
	 * @throws \Exception when select or insert fails
	 */
	private function _getBusinessDetailsForFeedback($business) {
	    $businessService = new \Services\Business();
	    $business = $businessService->getBusinessByCode($business);
	    //business not in db, need to update! FIXME: is this still good idea?
	    if (!$business) {
	        $business = $businessService->insertTemplate($business);
	    }
	    $talker = $businessService->getTableTalker($business);
	    //set business object in template
	    $this->_smarty->assign('business', $business);
	    //assign tabletalker specific information for feedabck form (question)
	    //FIXME: translations are not included at the moment
	    $this->_smarty->assign('tabletalker', $talker);
	}
	
	/**
	 * Method stores feedback to database when lastPostTime token allows this
	 * @param array $post HTML POST array
	 */
	public function save($post) {
	    //on a session base, check posting time and if current session has 
	    //posted in last 12 hours. If so, then deny post!
	    $token = @$_SESSION['lastPostTime_'.$post['code']];
	    if (!isset($token) || time() > strtotime('+12 hours', $token)) {
	        //however if this is fresh post, then try to save
	        try {
	            //determine returning user
	            $userService = new \Services\User();
	            $user = $userService->findUserByEmailOrPhone($post['email'], $post['phone']);
	            //new user? then insert to db
	            if (!$user && (strlen($post['email']) > 0 || strlen($post['phone'])) > 0) {
	                $post['uid'] = $userService->prepareInsert($post);
	            } else if ($user) {
	                $post['uid'] = $user->getId();
	            } else {
	                $post['uid'] = 0;
	            }
    	        if ($fb = $this->_service->prepareInsert($post)) {
    	            $_SESSION['lastPostTime_'.$post['code']] = time();
    	            $message = array('success' => $this->_translation['feedbackSent']);
    	            //send manager a notification email (out from this function)
    	            $businessService = new \Services\Business();
    	            $businessService->notifyManager($fb);
    	        } else {
    	            $message = array('error' => $this->_translation['feedbackNotSent']);
    	        }
	        } catch (\Exception $e) {
	            //save fails due database, event logged to syslog, inform user only
	            $message = array('error' => 'Internal error occurred! Check back later!');
	        }
	    } else {
	        $message = array('warning' => $this->_translation['alreadyPosted']);
	    }
	    
	    //if not mobile view then show details page with message, otherwise only
	    //message
	    if ($post['mobile'] == 0) {
	        try {
    	        $business = new \Entities\Business();
    	        $business->setCode(\Misc\Tools::cleanInput($post['code']));
    	        $business = $this->_service->select($business);
    	        
    	        $view = new \Views\Business();
    	        $view->setMessage($message);
    	        $view->viewDetails($business->getId());
	        } catch (\Exception $e) {
    	        //error is already logged to syslog, only inform user!
    	        $this->_pagePanic();
    	    }
	    } else {
	        $this->_smarty->assign('messages', $message);
	        $this->_smarty->assign('content', '');
	        $this->_smarty->display('portable.tpl');
	    }
	}
	
	/**
	 * Method deletes feedback via ajax request when logged in user is admin
	 * @param int $id feedback id
	 * @return void
	 */
	public function delete($id) {
	    //check if user has the privileges to perform this action
		if ($this->_loggedInUser && $this->_loggedInUser->getType() == \Enum\AccountType::Admin) {
			$template = new \Entities\Feedback();
			$template->setId($id);
			try {
			    $this->_service->delete($template);
			} catch (\Exception $e) {
			    //somehow display error or sth, logging is handled in service
			}
		}
	}
	
	/**
	 * Method marks comment as inappropriate (via ajax)
	 * @param array $post
	 * @return void
	 */
	public function markInappropriate($post) {
		$id = \Misc\Tools::cleanInput($post['comId']);
		//only try marking as inappropriate when id is acceptable
		if ($id > 0) {
			$reason = \Misc\Tools::cleanInput($post['reason']);
			try {
			    $com = $this->_service->markInappropriate($id);

			    //Create new entry for feedback
			    $iafbServ = new \Services\InappropriateFeedback();
			    $iafbServ->prepareInsert($com, $reason);
			    
			    //notify
			    $to = 'markuskarileet@hotmail.com';
			    $subject = 'Ebasobiv kommentaar';
			    $body = sprintf('Kommentaar: <p>%s</p> Märgiti ebasobivaks järgneval põhjusel: <p>%s</p> <a href="%s">Link</a>', $com->getComment(), $reason, WWW . WEBROOT . '/companyDetails/'.$com->getBusiness() . '#feedback_'.$com->getId());
			    $altBody = sprintf('Kommentaar: %s märgiti ebasobivaks järgneval põhjusel: %s', $com->getComment(), $reason);
			    \Misc\Tools::sendEmail($to, $subject, $body, $altBody);
			} catch (\Exception $e) {
			    //somehow display error or sth, logging is handled in service
			}
		}
	}
}